﻿<template>
  <a-drawer
    :title="title"
    width="90%"
    :confirmLoading="loading"
    placement="right"
    :visible="visible"
    @close="
      () => {
        this.visible = false
      }
    "
    :body-style="{ paddingBottom: '80px' }"
  >
    <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="订单号" prop="OrderId">
            <InStorageSelect v-model="entity.OrderId" :disabled="disabled" @select="RefCodeSelect" />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收货类型" prop="Type">
            <a-select v-model="entity.Type" >
              <a-select-option
                v-for="(item, index) in TypeList"
                :value="item.DicValue"
                :key="index"
              >{{ item.DicName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <!-- <a-form-model-item label="供货单位" prop="SupId" v-if="entity.Type !== 'Purchase'">
            <sup-select v-model="entity.SupId" :disabled="disabled"></sup-select>
          </a-form-model-item> -->
          <a-form-model-item label="供货单位" prop="SuppName">
            <a-input v-model="entity.SuppName" disabled />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="8">
          <a-form-model-item label="订单时间" prop="OrderTime">
            <a-date-picker v-model="entity.OrderTime" :style="{ width: '100%' }" :allowClear="false" disabled />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="收货时间" prop="RecTime">
            <a-date-picker
              v-model="entity.RecTime"
              :style="{ width: '100%' }"
              :allowClear="false"
              :disabled="disabled"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="8">
          <a-form-model-item label="备注" prop="Remarks">
            <a-textarea v-model="entity.Remarks" :disabled="disabled" autocomplete="off" />
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>
    <div style="position: relative;">
      <a-button
        type="primary"
        @click="addMaterial"
        style="margin-right: 10px;position: absolute;right: 0;top: 13px;z-index: 999;"
        v-if="title === '新建' || title === '编辑'"
      >添加物品</a-button
      >
      <a-tabs default-active-key="1">
        <a-tab-pane key="1" tab="物品明细">
          <a-table
            :columns="title === '查看' || title === '审核' ? columnslook : columnsPurchase"
            :data-source="dataArr"
            :loading="loading"
            :pagination="false"
            :rowKey="(row, index) => row.rowId"
            size="small"
            bordered
          >
            <template slot="action" slot-scope="text, record, index">
              <span>
                <a :disabled="disabledtable" @click="rowcopy(record, index)">复制</a>
                <a-divider type="vertical" />
              </span>
              <a-popconfirm title="确定删除吗?" @confirm="() => del(record, index)">
                <a :disabled="disabledtable">删除</a>
              </a-popconfirm>
            </template>
            <template slot="dataIndex" slot-scope="text, record, index">
              <span>{{ (pagination.current - 1) * pagination.pageSize + index + 1 }}</span>
            </template>
            <template slot="RecNum" slot-scope="text, record, index">
              <a-input
                type="number"
                v-model="record.RecNum"
                :disabled="disabledtable"
                @change="RecNumchange($event, record)"
                style="width: 100%; text-align: right"
              />
            </template>
            <template slot="Batch" slot-scope="text, record, index">
              <a-input v-model="record.Batch" :disabled="disabledtable || !record.IsBatch" />
              <!-- <span v-else>{{ record.Batch }}</span> -->
            </template>
            <template slot="Starttime" slot-scope="text, record, index">
              <a-date-picker
                v-if="record.IsPeriodOfValidity"
                v-model="record.Starttime"
                :style="{ width: '100%' }"
                :disabled="disabledtable || !record.IsBatch"
                @change="Starttimechange($event, record)"
                :allowClear="false"
              />
            </template>
            <template slot="Endtime" slot-scope="text, record, index">
              <a-date-picker
                v-if="record.IsPeriodOfValidity"
                v-model="record.Endtime"
                :style="{ width: '100%' }"
                :disabled="disabledtable || !record.IsBatch"
                :allowClear="false"
                @change="Endtimechange($event, record)"
              />
            </template>
            <template slot="Amount" slot-scope="text, record, index">
              <span>{{ AmountNum(record) }}</span>
            </template>
            <template slot="Price" slot-scope="text, record">
              <a-input
                size="small"
                class="input"
                disabled
                type="number"
                v-model="record.Price"
                style="text-align: right;"
              ></a-input>
            </template>
<!--            <template slot="Rate" slot-scope="text, record">-->
<!--              <enum-select code="TaxRate" v-model="record.Rate" :disabled="disabledtable"></enum-select>-->
<!--              &lt;!&ndash; <a-input-->
<!--                size="small"-->
<!--                class="input"-->
<!--                :disabled="disabled"-->
<!--                type="number"-->
<!--                v-model="record.Price"-->
<!--                style="text-align: right;"-->
<!--              ></a-input> &ndash;&gt;-->
<!--            </template>-->
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>

    <div
      :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1
      }"
    >
      <a-button
        :style="{ marginRight: '8px' }"
        @click="
          () => {
            this.visible = false
          }
        "
      >取消</a-button
      >

      <a-button
        type="primary"
        @click="handleSubmit"
        :loading="loading"
        v-if="title === '新建' || title === '编辑'"
      >保存</a-button
      >
      <a-button type="primary" @click="audin" :loading="loading" v-if="title === '审核'">审核通过</a-button>
    </div>
    <MaterialChoose ref="MaterialChoose" @onChoose="chengadd"></MaterialChoose>
  </a-drawer>
</template>

<script>
import InStorageSelect from '@/components/hospitalComponents/InStorageSelect.vue'
import MaterialChoose from './MaterialChoose'
import moment from 'moment'
export default {
  components: {
    MaterialChoose,
    InStorageSelect
  },
  props: {
    parentObj: { type: Object, required: true },
    disabled: { type: Boolean, required: false, default: false }
  },
  data () {
    return {
      TypeList: [],
      Id: '',
      disabledtable: false,
      pagination: {
        current: 1,
        pageSize: 25,
        showTotal: (total, range) => `总数:${total} 当前:${range[0]}-${range[1]}`,
        pageSizeOptions: ['25', '50', '100'], // 设置pageSize的可选值，页面啊可以通过下拉框进行选择
        showSizeChanger: true,
        onShowSizeChange: (current, pageSize) => (this.pageSize = pageSize)
      },
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'dataIndex' },
          width: '50px'
        },
        {
          title: '物品编号',
          dataIndex: 'Code',
          ellipsis: true
        },

        { title: '物品名称', dataIndex: 'Name' },
        {
          title: '物品规格',
          dataIndex: 'Spec',

          ellipsis: true
        },
        {
          title: '仓储单位',
          dataIndex: 'StorageName',

          ellipsis: true
        },
        {
          title: '数量',
          width: '100px',
          dataIndex: 'RecNum',
          ellipsis: true,
          scopedSlots: { customRender: 'RecNum' },
          align: 'right'
        },
        { title: '单价', dataIndex: 'Price', align: 'right', scopedSlots: { customRender: 'Price' } },
        { title: '金额', dataIndex: 'Amount', align: 'right', scopedSlots: { customRender: 'Amount' } },
        { title: '税率%', dataIndex: 'Rate', align: 'right', ellipsis: true },
        {
          title: '批次管理',
          width: '47px',
          dataIndex: 'IsBatch',
          customRender: value => {
            return value ? '是' : '否'
          }
        },
        {
          title: '批次号',
          dataIndex: 'Batch',
          scopedSlots: { customRender: 'Batch' }
        },
        {
          title: '生产日期',
          dataIndex: 'Starttime',
          width: '140px',
          scopedSlots: { customRender: 'Starttime' }
        },
        {
          title: '保质期单位',
          dataIndex: 'PeriodOfValidityUnit',
          width: '60px'
        },
        {
          title: '保质期',
          dataIndex: 'PeriodOfValidity',
          align: 'right',
          width: '60px'
        },
        {
          title: '失效日期',
          dataIndex: 'Endtime',
          width: '140px',
          scopedSlots: { customRender: 'Endtime' }
        },

        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '130px' }
      ],
      columnsPurchase: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'dataIndex' },
          width: '50px'
        },
        { title: '物品编号', dataIndex: 'Code', ellipsis: true },

        { title: '物品名称', dataIndex: 'Name' },
        {
          title: '物品规格',
          dataIndex: 'Spec',

          ellipsis: true
        },
        {
          title: '仓储单位',
          dataIndex: 'StorageName',

          ellipsis: true
        },
        {
          title: '剩余收货数量',
          dataIndex: 'SurplusNums',
          ellipsis: true,

          align: 'right'
        },
        {
          title: '数量',
          dataIndex: 'RecNum',
          width: '100px',
          ellipsis: true,
          scopedSlots: { customRender: 'RecNum' },
          align: 'right'
        },
        { title: '单价', dataIndex: 'Price', align: 'right', scopedSlots: { customRender: 'Price' } },
        { title: '金额', dataIndex: 'Amount', align: 'right', ellipsis: true, scopedSlots: { customRender: 'Amount' } },
        { title: '税率%', dataIndex: 'Rate', align: 'right', ellipsis: true},
        {
          title: '批次管理',
          dataIndex: 'IsBatch',
          width: '47px',
          customRender: value => {
            return value ? '是' : '否'
          }
        },
        {
          title: '批次号',
          dataIndex: 'Batch',
          scopedSlots: { customRender: 'Batch' }
        },
        {
          title: '生产日期',
          dataIndex: 'Starttime',
          width: '140px',
          scopedSlots: { customRender: 'Starttime' }
        },
        {
          title: '保质期单位',
          dataIndex: 'PeriodOfValidityUnit',
          width: '60px'
        },
        {
          title: '保质期',
          dataIndex: 'PeriodOfValidity',
          align: 'right',
          width: '60px'
        },
        {
          title: '失效日期',
          dataIndex: 'Endtime',
          width: '140px',
          scopedSlots: { customRender: 'Endtime' }
        },

        { title: '操作', dataIndex: 'action', scopedSlots: { customRender: 'action' }, width: '130px' }
      ],
      columnslook: [
        {
          title: '序号',
          dataIndex: 'index',
          scopedSlots: { customRender: 'dataIndex' },
          width: '50px'
        },
        { title: '物品编号', dataIndex: 'Code', ellipsis: true },

        { title: '物品名称', dataIndex: 'Name' },
        {
          title: '物品规格',
          dataIndex: 'Spec',

          ellipsis: true
        },
        {
          title: '仓储单位',
          dataIndex: 'StorageName',

          ellipsis: true
        },
        {
          title: '数量',
          dataIndex: 'RecNum',
          width: '100px',
          ellipsis: true,
          scopedSlots: { customRender: 'RecNum' },
          align: 'right'
        },
        { title: '单价', dataIndex: 'Price', align: 'right', scopedSlots: { customRender: 'Price' } },
        { title: '金额', dataIndex: 'Amount', align: 'right', ellipsis: true, scopedSlots: { customRender: 'Amount' } },
        { title: '税率%', dataIndex: 'Rate', align: 'right', ellipsis: true },
        {
          title: '入库数量',
          dataIndex: 'InNum',
          ellipsis: true,

          align: 'right'
        },
        {
          title: '批次管理',
          width: '47px',
          dataIndex: 'IsBatch',
          customRender: value => {
            return value ? '是' : '否'
          }
        },
        {
          title: '批次号',
          dataIndex: 'Batch',
          scopedSlots: { customRender: 'Batch' }
        },
        {
          title: '生产日期',
          dataIndex: 'Starttime',
          width: '140px',
          scopedSlots: { customRender: 'Starttime' }
        },
        {
          title: '保质期单位',
          dataIndex: 'PeriodOfValidityUnit',
          width: '60px'
        },
        {
          title: '保质期',
          dataIndex: 'PeriodOfValidity',
          align: 'right',
          width: '60px'
        },
        {
          title: '失效日期',
          dataIndex: 'Endtime',
          width: '140px',
          scopedSlots: { customRender: 'Endtime' }
        }
      ],
      dataArr: [],

      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 }
      },
      visible: false,
      loading: false,
      entity: { Id: '', Status: 0, OrderId: null, SupId: null, SuppName: null },
      listDetail: [],
      title: '',
      ParentIdTreeData: [],
      rules: {
        OrderTime: [{ required: true, message: '请输入订单时间', trigger: 'change' }],
        RecTime: [{ required: true, message: '请输入收货时间', trigger: 'change' }],
        Type: [{ required: true, message: '请选择收货入库类型', trigger: 'change' }],
        OrderId: [{ required: true, message: '请选择采购订单', trigger: 'change' }],
        SupId: [{ required: true, message: '请选择供货单位', trigger: 'change' }],
        SuppName: [{ required: true, message: '请选择供货单位', trigger: 'change' }]
      }
    }
  },

  methods: {
    tableRepeatSrot (list, Code) {
      var obj = {}
      var indices = [] // 数组中每一个值是一个数组，数组中的每一个元素是原数组中相同zhuanye的下标
      list.map((item, index) => {
        // var codecopy = item[Code]
        // var _index = cache[codecopy]
        if (obj[item[Code]] === undefined) {
          // 每次obj对象里面没有code的时候 定义对象 然后indices数组push进去list数组中这个元素的下标
          obj[item[Code]] = {}

          indices.push([index]) // [ [0] ]
          obj[item[Code]].arrindex = indices.length - 1 //
          obj[item[Code]].items = [] //
          obj[item[Code]].items.push(item)
        } else {
          indices[obj[item[Code]].arrindex].push(index) // 如果有重复的就找到这个出现的数组 然后push进去 [[0][1,2]]
          obj[item[Code]].items.push(item)
        }
      })
      // console.log(obj, 'obj')
      // console.log(indices, 'indices')
      var arr = []
      indices.map(item => {
        // 然后循环根据indices数组里的每一项下标的list取出来重新赋值排序
        item.map(index => {
          arr.push(list[index])
        })
      })
      // console.log(arr, 'arr')
      // return result
      return arr
    },

    rowcopy (row, index) {
      var obj = { ...row }
      obj.rowId = new Date().valueOf() + index + ''
      obj.Batch = ''
      obj.RecNum = ''
      // obj.Price = 0
      obj.Amount = 0

      this.$set(obj, 'Rate', '')
      this.$set(obj, 'Starttime', null)
      this.$set(obj, 'Endtime', null)

      this.dataArr = [...this.dataArr, obj]
      this.dataArr = this.tableRepeatSrot(this.dataArr, 'MaterialId')
      // this.dataArr.sort((a, b) => {
      //   console.log(a)
      //   return Number(b.MaterialId) - Number(a.MaterialId)
      // })
    },
    AmountNum (record) {
      if (record.Price && record.RecNum) {
        record.Amount = (Number(record.Price) * Number(record.RecNum)).toFixed(2)
      } else {
        record.Amount = 0
      }
      return record.Amount
    },
    typechange () {
      this.dataArr = []
      this.entity.SupId = null
      this.entity.SuppName = null
      this.entity.OrderId = null
    },
    audin () {
      this.loading = true
      this.$http.post('/TD/TD_Receiving/SaveToExamine?ReceId=' + this.Id, {}).then(resJson => {
        this.loading = false
        if (resJson.Success) {
          this.$message.success('审核成功')
          this.visible = false
          this.parentObj.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    },
    RecNumchange (eve, row) {
      if (row.RecNum.split('.').length > 1) {
        this.$message.error('不能填写小数点')
        row.RecNum = Math.floor(Number(row.RecNum))
      }
      if (this.entity.Type === 'Purchase') {
        if (Number(row.RecNum) > Number(row.SurplusNums)) {
          this.$message.warning('数量建议不能大于剩余收货数量')
        }
      }
    },
    del (row, index) {
      this.dataArr.splice(index, 1)
    },
    Endtimechange (eve, row) {
      this.$set(row, 'EndDate', moment(eve).format('YYYY-MM-DD'))
    },
    Starttimechange (eve, row) {
      this.$set(row, 'StartDate', moment(eve).format('YYYY-MM-DD'))
      var str = ''
      if (row.PeriodOfValidityUnit === '年') {
        str = 'years'
      } else if (row.PeriodOfValidityUnit === '月') {
        str = 'months'
      } else if (row.PeriodOfValidityUnit === '日') {
        str = 'days'
      }

      this.$set(row, 'Endtime', moment(eve).add(Number(row.PeriodOfValidity), str))
      this.$set(
        row,
        'EndDate',
        moment(eve)
          .add(Number(row.PeriodOfValidity), str)
          .format('YYYY-MM-DD')
      )
    },
    chengadd (a) {
      console.log(a)
      a.forEach((item, index) => {
        this.$set(item, 'MaterialId', item.MaterialId)
        this.$set(item, 'Id', '')
        this.$set(item, 'RecNum', item.SurplusNums ? item.SurplusNums : null)
        this.$set(item, 'Endtime', null)
        this.$set(item, 'Starttime', null)
        this.$set(item, 'Price', item.Price ? item.Price : 0)
        this.$set(item, 'Batch', '')
        this.$set(item, 'Amount', 0)
        this.$set(item, 'Rate', item.Rate ? item.Rate : '')
        this.$set(item, 'rowId', new Date().valueOf() + index + '')
      })
      this.dataArr = [...this.dataArr, ...a]
      // this.dataArr.sort((a, b) => {
      //   console.log(a)
      //   return Number(b.MaterialId) - Number(a.MaterialId)
      // })
      this.dataArr = this.tableRepeatSrot(this.dataArr, 'MaterialId')
      console.log(this.dataArr)
      // a = [...this.dataArr, ...a]
      // var newobj = {}
      // // reduce 方法
      // var maparr = []
      // a = a.reduce((preVal, curVal) => {
      //   if (!newobj[curVal.Code]) {
      //     //如果这个对象里面没有对应的ID 就push进新数组 并给此ID赋值下次判断有这个ID就说明是重复
      //     preVal.push(curVal)
      //     newobj[curVal.Code] = curVal.Code
      //   } else {
      //     //如果有对应的ID就说明重复 数组里面有重复对象的MaterialId,添加到另外一个数组是重复的对象
      //     maparr.push(curVal)
      //   }
      //   return preVal
      // }, [])
      // if (maparr.length > 0) {
      //   this.$message.error('重复物品已筛选掉')
      // }

      // console.log(a, maparr)
      // this.dataArr = [...a]
    },
    addMaterial () {
      if (this.entity.OrderId) {
        this.$refs.MaterialChoose.openChoose(this.entity.OrderId)
      } else {
        this.$message.error('请选择订单号后添加物品')
      }
      // if (this.entity.Type === 'Purchase') {
      //   if (this.entity.OrderId) {
      //     this.$refs.MaterialChoose.openChoose(this.entity.OrderId)
      //   } else {
      //     this.$message.error('采购收货下请选择采购订单后添加物品')
      //   }
      // } else if (!this.entity.Type) {
      //   this.$message.error('请先选择收货类型后添加物品')
      // } else if (this.entity.Type === 'Consignment') {
      //   this.$refs.MaterialChoose.openChoose(null, true)
      // } else {
      //   this.$refs.MaterialChoose.openChoose()
      // }
    },

    RefCodeSelect (row) {
      this.dataArr = []
      // console.log(row)
      this.$set(this.entity, 'SuppName', row.SuppName)
      this.$set(this.entity, 'SupId', row.SupplierId)
      this.$set(this.entity, 'Type', row.Type)
      this.$set(this.entity, 'OrderTime', moment(row.PurchaseDate))
    },
    init () {
      this.visible = true
      this.entity = { RecTime: moment(), OrderId: null, SupId: null, SuppName: null }

      this.dataArr = []
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })

      this.TypeList = []
      this.$http.post('/Base_BasicData/Base_DictionaryMain/GetTheDataByDicKey', { Condition: 'DicKey', Keyword: 'ReceiveType' }).then(resJson => {
        this.loading = false
        this.TypeList = resJson.Data.DictionaryDetailsList
      })
    },

    digui (arr) {
      arr.forEach(item => {
        if (item.children != null) {
          item.disabled = true
          this.digui(item.children)
        } else {
          item.disabled = false
        }
      })
    },
    openForm (id, tit) {
      this.title = tit || '新建'
      this.init()
      this.disabledtable = false
      if (tit === '编辑') {
        this.disabledtable = false
      } else if (tit === '查看' || tit === '审核') {
        this.disabledtable = true
      }
      if (id) {
        this.Id = id
        this.loading = true
        this.$http.post('/TD/TD_Receiving/GetReceivingData?ReceId=' + id, {}).then(resJson => {
          this.loading = false
          if (resJson.Data == null) {
            this.$message.error('没有找到对应单据!')
            this.visible = false
          } else {
            this.entity = resJson.Data
            // console.log('表格', this.entity)
            this.entity.OrderTime = moment(this.entity.OrderTime)
            this.entity.RecTime = moment(this.entity.RecTime)
            resJson.Data.RecDetailMaterial.forEach((item, index) => {
              this.$set(item, 'rowId', new Date().valueOf() + index + '')
              this.$set(item, 'Endtime', item.EndDate ? moment(item.EndDate) : null)
              this.$set(item, 'Starttime', item.StartDate ? moment(item.StartDate) : null)
              item.Rate = item.Rate ? item.Rate : ''
            })

            this.dataArr = [...resJson.Data.RecDetailMaterial]
          }
        })
      }
    },
    handleSubmit () {
      this.$refs['form'].validate(valid => {
        if (!valid) {
          return
        }

        // 数据处理
        var ar = JSON.parse(JSON.stringify(this.dataArr))
        if (ar.length == 0) {
          this.$message.error('请添加明细信息')
          return
        }
        var arr = []
        ar.forEach(item => {
          if (item.IsBatch) {
            if (item.IsPeriodOfValidity) {
              if (Number(item.RecNum) <= 0 || !item.RecNum || !item.StartDate || !item.EndDate || !item.Batch) {
                arr.push(item)
              }
            } else {
              if (Number(item.RecNum) <= 0 || !item.RecNum || !item.Batch) {
                arr.push(item)
              }
            }
          } else {
            if (Number(item.RecNum) <= 0 || !item.RecNum) {
              arr.push(item)
            }
          }
          item.Rate = item.Rate ? item.Rate : ''
          item.EndDate = item.EndDate ? item.EndDate : null
          item.StartDate = item.StartDate ? item.StartDate : null
        })

        if (arr.length > 0) {
          this.$message.error('明细中数量或批次号或日期不正确，请核对')
          return
        }
        var entity = { ...this.entity }

        entity.OrderTime = moment(this.entity.OrderTime).format('YYYY-MM-DD')
        entity.RecTime = moment(this.entity.RecTime).format('YYYY-MM-DD')
        entity.RecDetails = ar
        this.loading = true
        this.$http.post('/TD/TD_Receiving/SaveReceivingData', entity).then(resJson => {
          if (resJson.Success) {
            this.$message.success('操作成功!')
            this.visible = false
            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
          this.loading = false
        })
      })
    },
    handleAudit (id, type) {
      this.loading = true
      this.$http.post('/TD/TD_Receiving/Approval', { Id: id, AuditType: type }).then(resJson => {
        this.loading = false
        if (resJson.Success) {
          this.$message.success('操作成功!')
          this.visible = false
          this.parentObj.getDataList()
        } else {
          this.$message.error(resJson.Msg)
        }
      })
    }
  }
}
</script>
